﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mjRegister.Entity;
using mjRegister.BAL;
using System.Threading;
using System.Text.RegularExpressions;

namespace mjRegister
{
    public partial class MyCar : Form
    {
        private ParkInfo _parkInfo;
        private User _user;
        private AccountInfo _accountInfo;
        bool userloginflag = false;
        IList<Thread> lstThread = new List<Thread>();

        private Form2 _ownerForm;

        private ListViewColumnSorter lvwColumnSorter;

        public MyCar(Form2 ownerForm,AccountInfo accountInfo)
        {
            _ownerForm = ownerForm;

            _accountInfo = accountInfo;

            //_user = user;

            InitializeComponent();

            lvwColumnSorter = new ListViewColumnSorter(0,1, 3);
            this.listView1.ListViewItemSorter = lvwColumnSorter;
        }

        delegate void DSetControlDisabled();
        void SetControlDisabled()
        {
            this.button1.Enabled = false;
            this.button3.Enabled = false;
            this.button4.Enabled = false;
            this.button2.Enabled = false;
            this.listView1.Enabled = false;
        }

        delegate void DRestoreControlEnabled();
        void RestoreControlEnabled()
        {
            this.button1.Enabled = true;
            this.button3.Enabled = true;
            this.button4.Enabled = true;
            this.listView1.Enabled = true;
            this.button2.Enabled = true;
        }

        delegate void DLoadParkInfo();
        void LoadParkInfo()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));
            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]加载[我的汽车]数据：\n",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            string verify = string.Empty;
            if (!userloginflag)
            {
                _user = new User();

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0}", _accountInfo.Email))));

                if (_user.Login(_accountInfo))
                {
                    this.Invoke(new DAppendText(_ownerForm.AppendText),
                      string.Format("[{0}]：[{1}]成功登录系统！",
                          DateTime.Now.ToString("HH:mm:ss"),
                            string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

                    userloginflag = true;

                    verify = _user.GetVerify();

                    this.Invoke(new DAppendText(_ownerForm.AppendText),
                      string.Format("[{0}]：获取VerifyCode：{1}",
                          DateTime.Now.ToString("HH:mm:ss"),
                            string.Format("{0}", verify)));

                    //_user.Logout();

                    //this.Invoke(new DAppendText(_ownerForm.AppendText),
                    //    string.Format("[{0}]：[{1}]退出系统！\n",
                    //        DateTime.Now.ToString("HH:mm:ss"),
                    //        string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

                }
                else
                    userloginflag = false;
            }
            else
                verify = _parkInfo.Verify;

            this.Invoke(new DAppendText(_ownerForm.AppendText),
             string.Format("[{0}]：[{1}]加载[我的汽车]数据……",
                 DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

            _parkInfo = Park.GetParkInfoByUid(verify, _user.UserInfo.uid);

            this.Invoke(new DInint(Init));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]加载[我的汽车]数据完成！\n",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));
            this.Invoke(new DRestoreControlEnabled(RestoreControlEnabled));
        }

        delegate void DAppendText(string text);
        delegate void DInint();
        void Init()
        {
            this.listView1.Items.Clear();

            this.label1.Text = string.Format("[我的汽车]数据：车({0})：{1} 现金：{2} 总金额：{3}",
                _parkInfo.CarInfos.Count.ToString(),
                _parkInfo.ParkAmountInfo.AllCarAmount.ToString(),
                _parkInfo.ParkAmountInfo.Cash.ToString(),
                _parkInfo.ParkAmountInfo.TotalAmount.ToString());

            string re = ".*?-(?<color>\\d+).gif";
            for (int i = 0; i < _parkInfo.CarInfos.Count; i++)
            {
                CarInfo carInfo = _parkInfo.CarInfos[i];

                string color = "未获取";

                try
                {
                    if (Regex.IsMatch(carInfo.car_logo_big, re))
                    {
                        color = Regex.Match(carInfo.car_logo_big, re).Result("${color}");
                        color = ((CarColor)int.Parse(color)).ToString();
                    }
                }
                catch {
                    color = "未获取";
                }
                ListViewItem listViewItem = new ListViewItem(
                    new string[]{
                        (i+1).ToString(),
                        carInfo.carid.ToString(),
                        string.Format("{0}，{1}，{2}",
                            carInfo.car_name,
                            color,
                            carInfo.park_profit.ToString()),
                        carInfo.price.ToString(),
                        (carInfo.park_uid == 0 ? "没在停车位" : (carInfo.park_uid <= 2 ? "[邻居]" + carInfo.park_real_name.ToString() : carInfo.park_real_name))
                    });

                listViewItem.Tag = carInfo;

                this.listView1.Items.Add(listViewItem);
            }

            this.label2.Text = "[我的汽车]数据加载完成。";
        }

        private void MyCar_Load(object sender, EventArgs e)
        {
            this.Text = string.Format("我的汽车：{0}", string.Format("{0}，{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name));
            this.label2.Text = "正在加载[我的汽车]数据，请稍候……";
            Thread t = new Thread(new ThreadStart(LoadParkInfo));
            t.Start();
            lstThread.Add(t);
        }

        private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //for (int i = 0; i < this.listView1.Items.Count; i++)
            //{
            //    ListViewItem listViewItem = this.listView1.Items[i];
            //    if (i != e.Index)
            //        listViewItem.Checked = false;
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_parkInfo.CarInfos.Count != 10)
            {
                CarMarket carMarket = new CarMarket(_parkInfo, CarAction.买车, _user,_ownerForm);
                if (carMarket.ShowDialog() == DialogResult.OK)
                {
                    this.label2.Text = "重新加载[我的汽车]数据，请稍候……";
                    Thread t = new Thread(new ThreadStart(LoadParkInfo));
                    t.Start();
                    lstThread.Add(t);
                }
            }
            else
                MessageBox.Show("你的汽车数量已经达到10辆，不能再购买新车了。");
        }

        IList<CarInfo> GetCheckedCarInfos()
        {
            IList<CarInfo> carInfos = new List<CarInfo>();

            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                ListViewItem listViewItem = this.listView1.Items[i];
                if (listViewItem.Checked)
                    carInfos.Add((CarInfo)listViewItem.Tag);
            }

            return carInfos;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            IList<CarInfo> carInfos = GetCheckedCarInfos();

            if (carInfos.Count > 0)
            {
                CarTrade(CarAction.换购新车, carInfos);
            }
            else
                MessageBox.Show("尚未选择项！");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.listView1.Items.Count > 1)
            {
                IList<CarInfo> carInfos = GetCheckedCarInfos();

                if (carInfos.Count > 0)
                {
                    CarTrade(CarAction.卖车, carInfos);
                }
                else
                    MessageBox.Show("尚未选择项！");
            }
            else
                MessageBox.Show("你只有一辆汽车，按照游戏规则不能卖出！");
        }

        private void MyCar_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
        }

        public void Stop()
        {
            lstThread = lstThread.Where(t => t.IsAlive).ToList();

            if (lstThread.Count > 0)
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：正在中断当前执行线程……",
                        DateTime.Now.ToString("HH:mm:ss")));

                for (int i = 0; i < lstThread.Count; i++)
                {
                    lstThread[i].Abort();
                }

                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：中断当前执行线程完成！\n",
                        DateTime.Now.ToString("HH:mm:ss")));
            }
        }

        void CarTrade(CarAction carAction, CarInfo carInfo)
        {
            IList<CarInfo> carInfos = new List<CarInfo>();
            carInfos.Add(carInfo);
            CarTrade(carAction, carInfos);
        }

        void CarTrade(CarAction carAction, IList<CarInfo> carInfos)
        {
            CarInfo carInfo = carInfos[0];
            if (carAction == CarAction.卖车)
            {
                if (MessageBox.Show(string.Format("确定卖掉：{0} 吗", string.Join(",",GetArray<string>.Get(carInfos.Select(c => c.car_name).ToList()))), "请确定", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    this.Invoke(new DAppendText(_ownerForm.AppendText),
                        string.Format("[{0}]：[{1}]卖车：\n",
                            DateTime.Now.ToString("HH:mm:ss"),
                              string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

                    StringBuilder sbCardRecycleMessage = new StringBuilder();

                    for (int i = 0; i < carInfos.Count; i++)
                    {
                        carInfo = carInfos[i];

                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                            string.Format("[{0}]：[{1}]查询是否拥有旧车回收卡：",
                                DateTime.Now.ToString("HH:mm:ss"),
                                  string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));
                        if (!_user.HasRecycleCard())
                        {
                            this.Invoke(new DAppendText(_ownerForm.AppendText),
                                string.Format("[{0}]：[{1}]没有旧车回收卡！\n",
                                    DateTime.Now.ToString("HH:mm:ss"),
                                      string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

                            if (_parkInfo.ParkAmountInfo.Cash == 0 || _parkInfo.ParkAmountInfo.Cash >= 10000)
                            {
                                this.Invoke(new DAppendText(_ownerForm.AppendText),
                                    string.Format("[{0}]：[{1}]当现金大于10000时购买旧车回收卡：",
                                        DateTime.Now.ToString("HH:mm:ss"),
                                          string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));

                                this.Invoke(new DAppendText(_ownerForm.AppendText),
                                    string.Format("[{0}]：[{1}]：{2}\n",
                                        DateTime.Now.ToString("HH:mm:ss"),
                                          string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                          Park.BuyCard(_parkInfo.Verify, "2")));

                                _parkInfo.ParkAmountInfo.Cash -= 10000;
                            }
                            else
                            {
                                MessageBox.Show("你现金不足，无法购买旧车回收卡！");
                                return;
                            }
                        }
                        else
                        {
                            this.Invoke(new DAppendText(_ownerForm.AppendText),
                                string.Format("[{0}]：[{1}]已拥有旧车回收卡！\n",
                                    DateTime.Now.ToString("HH:mm:ss"),
                                      string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));
                        }

                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                            string.Format("[{0}]：[{1}]开始卖车：{2}",
                                DateTime.Now.ToString("HH:mm:ss"),
                                  string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                  string.Format("[{0},{1}]", carInfo.carid.ToString(), carInfo.car_name)));

                        string cardRecycleMessage = Park.CardRecycle(_parkInfo.Verify, "2", carInfo.carid.ToString());

                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                            string.Format("[{0}]：[{1}]：{2}\n",
                                DateTime.Now.ToString("HH:mm:ss"),
                                  string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                  cardRecycleMessage));

                        sbCardRecycleMessage.AppendLine(cardRecycleMessage);
                    }

                    MessageBox.Show(sbCardRecycleMessage.ToString());

                    this.label2.Text = "重新加载[我的汽车]数据，请稍候……";
                    Thread t = new Thread(new ThreadStart(LoadParkInfo));
                    t.Start();
                    lstThread.Add(t);
                }
            }
            else if (carAction == CarAction.换购新车)
            {
                CarMarket carMarket = new CarMarket(_parkInfo, CarAction.换购新车, carInfos, _user, _ownerForm);
                if (carMarket.ShowDialog() == DialogResult.OK)
                {
                    this.label2.Text = "重新加载[我的汽车]数据，请稍候……";
                    Thread t = new Thread(new ThreadStart(LoadParkInfo));
                    t.Start();
                    lstThread.Add(t);
                }
            }
            else if (carAction == CarAction.送车)
            {
                FriendsManage friendsManage = new FriendsManage(_ownerForm,_accountInfo,carInfo);
                friendsManage.ShowDialog();
                this.label2.Text = "重新加载[我的汽车]数据，请稍候……";
                Thread t = new Thread(new ThreadStart(LoadParkInfo));
                t.Start();
                lstThread.Add(t);
            }
        }

        private void 换购新车ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                IList<CarInfo> carInfos = new List<CarInfo>();
                for (int i = 0; i < this.listView1.SelectedItems.Count; i++)
                {
                    carInfos.Add((CarInfo)this.listView1.SelectedItems[i].Tag);
                }
                CarTrade(CarAction.换购新车, carInfos);
            }
        }

        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (this.listView1.SelectedItems.Count > 0)
                {
                    this.contextMenuStrip1.Show((Control)sender, new Point(e.X, e.Y));
                }
            }
        }

        private void 卖车ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                IList<CarInfo> carInfos = new List<CarInfo>();
                for (int i = 0; i < this.listView1.SelectedItems.Count; i++)
                {
                    carInfos.Add((CarInfo)this.listView1.SelectedItems[i].Tag);
                }
                CarTrade(CarAction.卖车, carInfos);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.listView1.Items.Count > 1)
            {
                IList<CarInfo> carInfos = GetCheckedCarInfos();

                if (carInfos.Count > 0)
                {
                    CarTrade(CarAction.送车, carInfos[0]);
                }
                else
                    MessageBox.Show("尚未选择项！");
            }
            else
                MessageBox.Show("你只有一辆汽车，按照游戏规则不能送车！");

        }

        private void 送车ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                CarInfo carInfo = (CarInfo)this.listView1.SelectedItems[0].Tag;
                CarTrade(CarAction.送车, carInfo);
            }
        }

        IList<CarMarketInfo> carMarketInfos = new List<CarMarketInfo>();

        private void button5_Click(object sender, EventArgs e)
        {
            carMarketInfos = BAL.CarMarket.GetCarMarketInfos();

            for (int i = 6; i < this.listView1.Items.Count; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(aa));
                t.Start(this.listView1.Items[i].Tag);
                lstThread.Add(t);
            }
        }

        void aa(object obj)
        {
            CarInfo carInfo = (CarInfo)obj;

            string color = "0";

            string re = ".*?-(?<color>\\d+).gif";

            try
            {
                if (Regex.IsMatch(carInfo.car_logo_big, re))
                {
                    color = Regex.Match(carInfo.car_logo_big, re).Result("${color}");
                    color = ((CarColor)int.Parse(color)).ToString();
                }
            }
            catch
            {
                color = "0";
            }

            this.Invoke(new DAppendText(_ownerForm.AppendText),
                string.Format("[{0}]：[{1}]",
                    DateTime.Now.ToString("HH:mm:ss"),
                      Park.UpdateCar(_parkInfo.Verify, carInfo.carid.ToString(), carMarketInfos[70].CarId.ToString(), color)));

            this.Invoke(new DAppendText(_ownerForm.AppendText),
                string.Format("[{0}]：[{1}]",
                    DateTime.Now.ToString("HH:mm:ss"),
                      Park.PurchaseCar(_parkInfo.Verify, carMarketInfos[72].CarId.ToString(), color)));

        }

        private void button6_Click(object sender, EventArgs e)
        {
            carMarketInfos = BAL.CarMarket.GetCarMarketInfos();

            for (int i = 6; i < this.listView1.Items.Count; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(bb));
                t.Start(this.listView1.Items[i].Tag);
                lstThread.Add(t);
            }
        }

        void bb(object obj)
        {
            CarInfo carInfo = (CarInfo)obj;

            CarTrade(CarAction.卖车, carInfo);
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // 检查点击的列是不是现在的排序列.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // 重新设置此列的排序方法.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // 用新的排序方法对ListView排序
            this.listView1.Sort();

        }

    }
}

